﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace SmartMathLibrary.Storage
{
    /// <summary>
    /// The WeakPointStorage class provides methods, which clean the storage automatically 
    /// by the GC after an unspecified time. If other objects reference to the current data point
    /// the object instance will not be removed.
    /// </summary>
    [Serializable]
    public class WeakPointStorage
    {
        /// <summary>
        /// The dictionary for the point redirection.
        /// </summary>
        private static Dictionary<int, WeakReference> cache;

        /// <summary>
        /// Initializes a new instance of the <see cref="WeakPointStorage"/> class.
        /// </summary>
        /// <param name="size">The size of the storage.</param>
        public WeakPointStorage(int size)
        {
            cache = new Dictionary<int, WeakReference>();
        }

        /// <summary>
        /// Gets the size of the storage.
        /// </summary>
        /// <value>The size of the storage.</value>
        public int StoreageSize
        {
            get { return cache.Count; }
        }

        /// <summary>
        /// Determines whether the point data at the specified index is alive.
        /// </summary>
        /// <param name="index">The index of the point which should be checked.</param>
        /// <returns>
        /// 	<c>true</c> if the point instance at the specified index is alive; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAlive(int index)
        {
            return cache[index].IsAlive;
        }

        /// <summary>
        /// Gets or sets the <see cref="SmartMathLibrary.Storage.WeakPointStorageData"/> at the specified index.
        /// </summary>
        /// <value>The specified index.</value>
        public WeakPointStorageData this[int index]
        {
            get
            {
                WeakPointStorageData data = cache[index].Target as WeakPointStorageData;

                if (data == null)
                {
                    return null;
                }

                return data;
            }

            set { cache[index] = new WeakReference(value, false); }
        }
    }
}